package com.yaml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.yaml.snakeyaml.Yaml;



public class YamlTest {

	public static void main(String[] args) {
		writeYaml();
		readYaml();
		readYamlToMap();
	}
	//生成Yaml文件
	public static void writeYaml(){
		Person parent = new Person();
		parent.setName("Mr.Smith");
		parent.setAge(45);
		parent.setSex("man");
		List<Person> children = new ArrayList<Person>();
		Person child1 = new Person();
		child1.setName("lily");
		child1.setAge(10);
		child1.setSex("femal");
		Person child2 = new Person();
		child2.setName("BOb");
		child2.setAge(15);
		child2.setSex("man");
		children.add(child1);
		children.add(child2);
		parent.setChildern(children);
		File file = new File("D:\\personYaml1.yaml");
		FileWriter fileWriter = null;
		try {
			fileWriter = new FileWriter(file);
			Yaml yaml = new Yaml();
			yaml.dump(parent,fileWriter);
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
	public static void readYaml(){
		File file = new File("D:\\personYaml1.yaml");
		FileReader fileReader = null;
		try {
			fileReader = new FileReader(file);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Yaml yaml = new Yaml();
		Person person  = yaml.loadAs(fileReader, Person.class);
		System.out.println(person);
	}
	public static void readYamlToMap(){
		File file = new File("D:\\personYaml.yaml");
		FileReader fileReader = null;
		try {
			fileReader = new FileReader(file);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Yaml yaml = new Yaml();
		Map map = (Map)yaml.load(fileReader);
		System.out.println(map.get("age"));
		List list = (List)(map.get("childern"));
		Map map2 = (Map) list.get(0);
		System.out.println(map2.get("age"));
	}
}
